package com.zrrd.straw1.controller;


import com.zrrd.straw1.entity.Answer;
import com.zrrd.straw1.service.IAnswerService;
import com.zrrd.straw1.service.impl.AnswerServiceImpl;
import com.zrrd.straw1.vo.AnswerVo;
import com.zrrd.straw1.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;


@RestController
@RequestMapping("/answers")
public class AnswerController {

    @Autowired
    IAnswerService answerService;


    @GetMapping("/{id}/solved")
    public   Result solved(@PathVariable Integer id,
                           @AuthenticationPrincipal UserDetails userDetails){
        boolean isaccept = answerService.accept(id, userDetails.getUsername());
        if (isaccept){
            return Result.accepted("采纳完成！");
        }else {
            return Result.notFound("采纳失败！");
        }

    }

    //1.如果参数不是很多，数据量不是很大，数据不敏感。
    //  可以先使用 Get 请求方式，省掉给参数起名的过程(名字不必先后端一致，后端自定义）
    //  请求方式可以优先考虑GET，参考 REST 风格语义。
    //GET  POST
    //  localhost:8080/answers/question?id=10&name=zs&email=zs@qq.com  html风格
    //  localhost:8080/answers/question/10/zs/zs@qq.com                RESTful风格
    @GetMapping("/question/{id}")
    public Result<List<Answer>>  questionAnswer( @PathVariable Integer id ){
        //控制器层先判断，如果有问题，可以节省后面执行的开销。
        //业务层再判断，是因为业务层不只向当前的控制器提供服务，对其它控制器或业务对象提供服务。
        //为了保证健壮性，有必要独立判断分析。
        if( id == null ){
            return Result.ok("id不存在！");
        }

        List<Answer> answers = answerService.getAnswersByQuestionId( id );
        return Result.ok( answers );
    }

    @PostMapping
    @PreAuthorize("hasRole('ROLE_TEACHER')")
    public Result PostAnswer(@Validated AnswerVo answerVo, BindingResult bindingResult,
                             @AuthenticationPrincipal UserDetails userDetails){
        if(bindingResult.hasErrors()){
            String msg = bindingResult.getFieldError().getDefaultMessage();
            return Result.unprocesableEntity(msg);
        }
        Answer answer = answerService.saveAnswer(answerVo,userDetails.getUsername());
        return Result.created( answer );
    }

}
